// useLottie.js
import { useEffect, useRef, useState } from "react";
import lottie from "lottie-web";

export default function useLottie({
  animationData,
  loop = true,
  autoplay = true,
}) {
  const containerRef = useRef(null);
  const animationInstance = useRef(null);

  const [isPlaying, setIsPlaying] = useState(autoplay);

  useEffect(() => {
    animationInstance.current = lottie.loadAnimation({
      container: containerRef.current,
      renderer: "svg",
      loop,
      autoplay,
      animationData,
    });

    return () => {
      animationInstance.current?.destroy();
    };
  }, [animationData, loop, autoplay]);

  // 播放
  const play = () => {
    animationInstance.current?.play();
    setIsPlaying(true);
  };

  // 暂停
  const pause = () => {
    animationInstance.current?.pause();
    setIsPlaying(false);
  };

  // 停止并回到第一帧
  const stop = () => {
    animationInstance.current?.stop();
    setIsPlaying(false);
  };

  // 跳转到指定帧（frame 从 0 开始）
  const goToFrame = (frame) => {
    animationInstance.current?.goToAndStop(frame, true);
    setIsPlaying(false);
  };

  return {
    containerRef, // ✅ 传给 <div ref={containerRef}>
    play,
    pause,
    stop,
    goToFrame,
    isPlaying,
  };
}
